package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author: atguigu
 * @create: 2024-04-02 10:28
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConstantProperties properties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 专辑封面，声音封面，主播头像进行文件图片上传
     *
     * @return 上传后MinIO文件在线地址
     */
    @Override
    public String fileUpload(MultipartFile file) {
        //1.业务校验-验证上传文件是否为图片,TODO 图片大小
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new GuiguException(400, "图片格式非法！");
            }

            //TODO 调用阿里云内容安全接口审核图片是否合法

            //2.调用MinIO客户端对象上传文件方法上传到MinIO
            //2.1 文件名称 形式 日期/UUID.后缀
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            String objectName = "/" + DateUtil.today() + "/" + IdUtil.randomUUID() + "." + extName;
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(properties.getBucketName())
                            .object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //3.拼接上传后文件在线地址
            return properties.getEndpointUrl() + "/" + properties.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("[专辑服务]文件上传接口异常：", e);
            throw new RuntimeException("文件上传接口异常" + e);
        }
    }
}
